package com.xzs.thinking.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.support.RequestContextUtils;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * @author : Iris.Xiao
 * @date : 2017/11/20 10:19
 * @description :
 */
@ApiIgnore//使用该注解忽略这个API
@Controller
public class HelloWorldController2 {
    @Autowired
    private MessageSource messageSource;

    @RequestMapping("/helloworldHtml")
    public String helloworldHtml(HttpServletRequest request,Map<String,Object> map){
        map.put("hello","from TemplateController.helloHtml");
        Locale locale = LocaleContextHolder.getLocale();
        Locale locale1= RequestContextUtils.getLocale(request);
        locale = Locale.US;//不是Locale.English
        String msg = messageSource.getMessage("welcome", null,locale);
        String msg2= messageSource.getMessage("welcome", null,locale1);
        System.out.println(msg);
        System.out.println(msg2);
        return"/helloworld";
    }
    @RequestMapping("/changeSessionLanauage")
    public String changeSessionLanauage(HttpServletRequest request, HttpServletResponse response, String lang){
        System.out.println(lang);
        LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
        if("zh".equals(lang)){
            localeResolver.setLocale(request, response, new Locale("zh", "CN"));
        }else if("en".equals(lang)){
            localeResolver.setLocale(request, response, new Locale("en", "US"));
        }
        return "redirect:/helloworldHtml";
    }

    /**
     * 文件上传具体实现方法;
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file")MultipartFile file){
        if(!file.isEmpty()){

            return"上传成功";
        }else{
            return"上传失败，因为文件是空的.";
        }
    }
    @RequestMapping("/batchupload")
    @ResponseBody
    public String batchupload(HttpServletRequest request){
        List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file");

        return"上传成功";

    }
}
